var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var config = require('../config').config,
  cookiesConfig = config.cookies;
var error = require('../util/error');
var utilString = require('../util/string');
var util = require('util');
var uCookieConfig = cookiesConfig.userinfo.key;

var UserSchema = new Schema({
  name: {
    type: String
  },
  password: {
    type: String
  },
  email: {
    type: String,
    unique: true
  },
  profile_image_url: {
    type: String,
  default:
    ''
  },
  /**/
  location: {
    type: Number,
  default:
    0
  },
  signature: {
    type: String,
  default:
    ''
  },
  /**/
  weibo: {
    type: String,
  default:
    ''
  },
  score: {
    type: Number,
  default:
    0
  },
  article_count: {
    type: Number,
  default:
    0
  },
  reply_count: {
    type: Number,
  default:
    0
  },
  follower_count: {
    type: Number,
  default:
    0
  },
  following_count: {
    type: Number,
  default:
    0
  },
  collect_article_count: {
    type: Number,
  default:
    0
  },
  /**/
  create_at: {
    type: Date,
  default:
    Date.now
  },
  update_at: {
    type: Date,
  default:
    Date.now
  },
  is_vip: {
    type: Boolean,
  default:
    false
  },
  level: {
    type: Number,
  default:
    0
  },
  active: {
    type: Boolean,
  default:
    true
  },
  role: {
    type: Number,
  default:
    0
  }
});

var User = mongoose.model('User', UserSchema);

UserSchema.pre('save', function(next) {
  var user = this;

  if(!user.name || user.name.length < 2 || user.name.length > 12) {
    return next(new error.VerificationError('用户名不得为空，并且不得少于2位或长于12位'));
  }
  if(!user.password || user.password.length < 6 || user.password.length > 12) {
    return next(new error.VerificationError('密码不得为空，并且不得少于6位或长于12位'))
  }
  if(!user.email || !utilString.verifyEmail(user.email)) {
    return next(new error.VerificationError('邮箱不得为空，或格式不正确'))
  }


  user.password = utilString.md5(user.password);

  User.findOne({
    $or: [{
      name: this.name
    }, {
      email: this.email
    }]
  }, function(err, doc) {
    if(doc) {
      return next(new error.VerificationError('用户名或邮箱已被注册'))
    } else {
      return next();
    }
  })
});

// UserSchema.pre('findOne', function(next) {
//   //查询有密码且未加密，加密后字符串会大于12(判断的很粗糙，暂时没别的办法)
//   if(this.password && this.password <= 12){
//     this.password = utilString.md5(this.password);
//   }
//   return next();
// });
User.prototype.createCookie = function(res, cookieDayTime) {
  var pData = '';
  pData += 'pId=';
  pData += this._id;
  pData += '&role=';
  pData += this.role;
  pData += '&ip=';
  pData += '127.0.0.1';
  // 加密
  pData = utilString.toEncrypt(pData);
  var config = {};
  if(cookieDayTime) {
    config.maxAge = cookieDayTime * 24 * 60 * 60;
  }
  res.cookie(uCookieConfig.p, pData, config);
  res.cookie(uCookieConfig.pName, this.name, config);
  res.cookie(uCookieConfig.pEmail, this.email, config);
}

User.Verify = function(req, res, next) {
  var pData = req.cookies[uCookieConfig.p],
    name = req.cookies[uCookieConfig.pName],
    email = req.cookies[uCookieConfig.pEmail];
  // 加密
  pData = utilString.toDecrypt(pData);
  var ary = pData.split('&');
  var dataObj = {};
  for(var i in ary) {
    var s = ary[i].split('=');
    dataObj[s[0]] = s[1];
  }

  if(name && email && dataObj.pId && dataObj.role && dataObj.ip) {
    req.verifyUser = true;
    req.user = {
      name: name,
      email: email,
      id: dataObj.pId,
      role: dataObj.role
    }
  } else {
    req.verifyUser = false;
    req.user = null;
  }
  return next();
}